import React,{useState} from "react";
import './Personal.less'
import {Button, Input} from 'antd';
import request from "../../../utils/axios";
import { useDispatch, useSelector } from "react-redux";
import {editPassword} from '../../../store/model/counter'


const Personal:React.FC=()=>{

    const {userId,userName,standingName,password} = useSelector((store:any)=>store.counter)
    const dispatch=useDispatch()


    const [oldPassword,setOldPassword]=React.useState<string>('')
    const [newPassword,setNewPassword]=React.useState<string>('')
    const [confirmPassword,setConfirmPassword]=React.useState<string>('')

    const [strength, setStrength] = useState(0);

    const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setNewPassword(e.target.value);
        setStrength(calculatePasswordStrength(e.target.value));
    };

    const calculatePasswordStrength = (password: string) => {
        let score = 0;
        if (password.length >= 6 && password.length <= 20) {
        score++;
        if (/\d/.test(password)) score++; // 包含数字
        if (/[a-z]/.test(password)) score++; // 包含小写字母
        if (/[A-Z]/.test(password)) score++; // 包含大写字母
        }
        return Math.min(score, 3); // 最多3项
    };

    const changePassword = async () => {
        if (oldPassword === '' || newPassword === '' || confirmPassword === '') {
            alert('请输入密码');
        } else {
            if(oldPassword!=password){
                alert('原密码错误');
            }else{
                if (newPassword !== confirmPassword) {
                    alert('两次密码不一致');
                } else {
                    try {
                        await request.put(`edituser/${userId}`,{password: newPassword});
                        alert('保存成功')
                        setOldPassword('');
                        setNewPassword('');
                        setConfirmPassword('');
                        setStrength(0);
                        dispatch(editPassword(newPassword));
                    } catch (error) {
                        console.error(error);
                    }
                }
            }
            
        }
    };

    return (
        <div className="wrj-personal-box">
            <p className="wrj-personal-p">个人资料</p>
            <div className="wrj-personal-info">
                <p style={{fontWeight:700}}>个人信息</p>
                <div className="wrj-personal-info-div">
                    <p>用户名：</p>
                    <p style={{marginLeft:'100px'}}>{userName}</p>
                </div>
                <div className="wrj-personal-info-div">
                    <p>身份：</p>
                    <p style={{marginLeft:'115px'}}>{standingName}</p>
                </div>
            </div>
            <div className="wrj-personal-info">
                <p style={{fontWeight:700}}>修改登录密码</p>
                <div className="wrj-personal-info-div">
                    <label>旧密码：</label>
                    <Input.Password type="password" value={oldPassword} onChange={(e)=>setOldPassword(e.target.value)} placeholder="请输入旧密码" style={{width:'20%',height:'40px',marginLeft:'100px'}}/>
                    <p style={{color:'#3478F6',fontSize:'12px',marginLeft:'15px',cursor:'pointer'}}>忘记密码</p>
                </div>
                <div>
                    <div className="wrj-personal-info-div">
                        <label>新密码：</label>
                        <Input.Password type="password" onChange={handlePasswordChange} value={newPassword} placeholder="请输入新密码" style={{width:'20%',height:'40px',marginLeft:'100px'}}/>
                        <p style={{color:'gray',fontSize:'12px',marginLeft:'15px'}}>支持6-20位字母数字组合</p>
                    </div>
                    <div className="wrj-personal-info-passworddiv">
                        <p style={{color:'rgba(49, 204, 49, 1)',fontSize:'12px',marginTop:'10px'}}>· 你的密码必须至少包含6个字符</p>
                        <p style={{color:'rgba(49, 204, 49, 1)',fontSize:'12px',marginTop:'10px'}}>· 你的密码不能完全是数字</p>
                        <div className="strength-meter">
                            <div className={`section ${strength >= 1 ? 'weak' : 'empty'}`}></div>
                            <div className={`section ${strength >= 2 ? 'medium' : 'empty'}`}></div>
                            <div className={`section ${strength >= 3 ? 'strong' : 'empty'}`}></div><br/> 
                        </div>
                        <p className="strength-text">密码强度：{['弱', '较弱', '中等', '强'][strength]}</p>
                    </div>
                </div>
                <div className="wrj-personal-info-div">
                    <label>确认密码：</label>
                    <Input.Password type="password" value={confirmPassword} onChange={(e)=>setConfirmPassword(e.target.value)} placeholder="请再次输入新密码" style={{width:'20%',height:'40px',marginLeft:'85px'}}/>
                </div>
            </div>
            <Button type="primary" style={{width:'100px',marginLeft:'160px',marginTop:'50px'}} onClick={changePassword}>保存</Button>
        </div>
    )
}

export default Personal